<template>
  <div class="box">
    <div class="left">
      <div class="Ltitle">
        <span>试卷分类</span>
        <img
          src="@/assets/images/questionBank/扩展2.png"
          alt=""
          @click="(formDialogOption.title = '添加'), (formDialog = true)"
        />
        <img
          src="@/assets/images/questionBank/delete.png"
          alt=""
          @click="(formDialogOption.title = '修改'), (formDialog = true)"
        />
      </div>
      <div class="Lline"></div>
      <div class="Ltree">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :highlight-current="true"
          :expand-on-click-node="true"
          :default-expand-all="false"
          :auto-expand-parent="false"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span v-if="data.reserve1 == 0" style="margin-right: 15px">{{
              node.label
            }}</span>
          </span>
        </el-tree>
      </div>
    </div>
    <div class="right">
      <div class="RForm">
        <el-form
          ref="form"
          :inline="true"
          :model="queryParams"
          label-width="80px"
        >
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="time"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="试题名称">
            <el-input
              placeholder="标题"
              size="mini"
              v-model="queryParams.examinationPaperSummaryName"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="getTableData"
              >搜索</el-button
            >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="reserForm"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <div>
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 15px"
            @click="createTestPaper"
            >创建试卷</el-button
          >
        </div>
      </div>

      <div class="rBottom">
        <div class="rItem" v-for="item in tableData">
          <div class="rItemLeft">
            <div>{{ item.examinationPaperSummaryName }}</div>
            <div>
              试卷分类：{{
                item.testPaperClassification &&
                item.testPaperClassification.testPaperClassificationName
              }}
            </div>
            <div>{{ item.createBy }}创建于：{{ item.createTime }}</div>
          </div>
          <div class="rItemRight">
            <div>
              {{ item.bigProblem }} 大题 <span>|</span>{{ item.questions }} 小题
              <span>|</span>总分{{ item.totalPoints }}分
            </div>
            <div>
              <el-button type="text" @click="releaseExam(item)"
                ><i class="el-icon-view"></i> 发布考试 </el-button
              >
              <el-button type="text" @click="goPreviewView(item)"
                ><i class="el-icon-view"></i> 预览</el-button
              >
              <el-button type="text" @click="editTestPaper(item)"
                ><i class="el-icon-edit"></i>编辑</el-button
              >
              <el-button type="text" @click="deletaPaper(item)"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div style="height: 60px">
        <pagination
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getTableData"
        />
        <!-- <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getTableData"
        /> -->
      </div>
    </div>

    <el-dialog
      :title="formDialogOption.title"
      :visible.sync="formDialog"
      width="30%"
    >
      <div class="formBox">
        <el-form ref="form" :model="classForm" label-width="120px">
          <el-form-item label="所属分类">
            <el-cascader
              :options="treeData"
              ref="cascader"
              v-model="cascaderValue"
              :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                emitPath: false,
              }"
              @change="changeClass"
              :disabled="topLevel"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="创建顶级分类"
            v-if="formDialogOption.title == '添加'"
          >
            <el-checkbox v-model="topLevel"></el-checkbox>
          </el-form-item>
          <el-form-item
            label="分类名称"
            v-if="formDialogOption.title == '添加'"
          >
            <el-input
              v-model="classForm.testPaperClassificationName"
            ></el-input>
          </el-form-item>
          <div v-if="formDialogOption.title == '修改'">
            <el-form-item label="修改顶级分类">
              <el-checkbox v-model="topLevel"></el-checkbox>
            </el-form-item>
            <el-form-item
              label="分类名称"
              v-for="(item, index) in childrenClass"
              :key="index"
            >
              <el-input v-model="item.name" style="width: 70%"></el-input>
              <span style="margin-left: 15px">
                <el-button type="text" size="mini" @click.stop="isEdit(item)"
                  >修改</el-button
                >
                <el-button type="text" size="mini" @click.stop="isDelete(item)"
                  >删除</el-button
                >
              </span>
            </el-form-item>
          </div>

          <div style="text-align: right">
            <el-button
              @click="isAdd"
              type="primary"
              v-if="formDialogOption.title == '添加'"
              >提交</el-button
            >
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listClassification,
  listSummary,
  addClassification,
  updateClassification,
  delClassification,
  delSummary,
} from "../../../api/examPaperLibrary";
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      treeData: [],

      defaultProps: {
        children: "children",
        label: "name",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        testPaperClassificationId: null,
        params: {},
        examinationPaperSummaryName: null,
      },
      total: 0,
      totalQuantity: 0,
      clickHandler: null, // 存储事件处理函数的引用
      mdata: null,
      oldBankId: "",
      formDialog: false,
      formDialogOption: {
        title: "添加",
      },
      classForm: {
        parentId: 0,
        tier: 1,
        testPaperClassificationName: "",
      },
      childrenClass: [],
      cascaderValue: "",
      topLevel: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      time: [],

      topLeveleEdit: false, //修改顶级
    };
  },
  updated() {
    //判断是否初始配置，若无则配置。
    if (!this.mathJax.isMathjaxConfig.bool) {
      this.mathJax.initMathjaxConfig();
    }
    this.$nextTick((_) => {
      //传入组件id，让组件被MathJax渲染
      this.mathJax.MathQueue("questionList-page");
    });
  },

  mounted() {
    this.getTreeList();
    this.getTableData();

    setTimeout(() => {
      //判断是否初始配置，若无则配置。
      if (!this.mathJax.isMathjaxConfig.bool) {
        this.mathJax.initMathjaxConfig();
      }
      this.$nextTick((_) => {
        //传入组件id，让组件被MathJax渲染
        this.mathJax.MathQueue("questionList-page");
      });
    }, 300);
  },
  watch: {
    formDialog: function (n, o) {
      if (!n) {
        this.childrenClass = [];
        this.cascaderValue = "";
        this.topLevel = false;
      }
    },
    topLevel: function (n, o) {
      if (n) {
        console.log(this.childrenClass);
        this.childrenClass = this.treeData;
      } else {
        this.childrenClass = [];
      }
    },
  },

  methods: {
    reserForm() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        testPaperClassificationId: null,
        params: {},
        examinationPaperSummaryName: null,
      };
      this.time = [];
      this.getTableData();
    },

    isAdd() {
      if (this.topLevel) {
        //----------------------------------------------------------
        if (this.classForm.testPaperClassificationName == "") {
          this.$message.warning("分类名称不能为空");
          return;
        }

        for (let i = 0; i < this.treeData.length; i++) {
          if (this.treeData[i].id == this.classForm.id) break;
          if (
            this.treeData[i].name == this.classForm.testPaperClassificationName
          ) {
            this.$message.warning("同层级不能有重名分类");
            return;
          }
        }

        if (this.classForm.type != null) {
        } else {
          let obj = {
            parentId: 0,
            testPaperClassificationName:
              this.classForm.testPaperClassificationName,
            tier: 1,
          };
          addClassification(obj).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.formDialog = false;
              this.getTreeList();
            }
          });
        }
        //----------------------------------------------------------
      } else {
        if (
          this.$refs.cascader.getCheckedNodes()[0] == null ||
          this.classForm.testPaperClassificationName == ""
        ) {
          this.$message.warning("父级或分类名称不能为空");
          return;
        }
        let node = this.$refs.cascader.getCheckedNodes()[0];
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].data.id == this.classForm.id) break;
          if (
            node.children[i].data.name ==
            this.classForm.testPaperClassificationName
          ) {
            this.$message.warning("同层级不能有重名分类");
            return;
          }
        }

        if (this.classForm.type != null) {
        } else {
          let obj = {
            parentId: this.classForm.parentId,
            testPaperClassificationName:
              this.classForm.testPaperClassificationName,
            tier: Number(node.data.type) + 1,
          };
          addClassification(obj).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.formDialog = false;
              this.getTreeList();
            }
          });
        }
      }
    },
    getToken() {
      return getToken();
    },

    getTreeList() {
      listClassification().then((res) => {
        this.treeData = res.rows;
        this.init(this.treeData);
      });
    },
    //点击树状图
    handleNodeClick(val) {
      // console.log(val);
      this.queryParams["testPaperClassificationId"] = val.id;

      this.getTableData();
    },

    init(data) {
      console.log(1, data);
      if (data && data.length === 0) return;
      console.log(2);
      for (let i = 0; i < data.length; i++) {
        if (typeof data[i] === "object" && data[i] !== null) {
          this.$set(data[i], "reserve1", 0);
        }
        if (Array.isArray(data[i].children) && data[i].children.length > 0) {
          this.init(data[i].children);
        }
      }

      console.log(3);
    },
    getTableData() {
      console.log(this.queryParams, this.time);
      if (this.time.length != 0) {
        (this.queryParams.params["beginCreateTime"] = this.time[0]),
          (this.queryParams.params["endCreateTime"] = this.time[1]);
      } else {
        this.queryParams.params = {};
      }

      listSummary(this.queryParams).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.totalQuantity = res.totalQuantity;
      });
    },
    addQuestions() {
      this.$router.push("/questionBank/questionBank/management/addQuestions");
    },
    //form表单所属分类
    changeClass(val) {
      this.classForm.parentId = val;

      let node = this.$refs.cascader.getCheckedNodes()[0];
      console.log(node);
      this.childrenClass = node.children;
    },
    isEdit(data) {
      for (let i = 0; i < this.childrenClass.length; i++) {
        if (this.childrenClass[i].id == data.id) continue;

        if (this.childrenClass[i].name == data.name) {
          this.$message.warning("同层级不能有重名分类");
          return;
        }
      }

      let obj = {
        testPaperClassificationId: data.id,
        testPaperClassificationName: data.name,
      };
      updateClassification(obj).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.getTreeList();
        }
      });
    },
    isDelete(data) {
      this.$confirm("此操作将删除分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delClassification(data.id).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.childrenClass = this.childrenClass.filter((ele) => {
                return ele.id != data.id;
              });
              this.getTreeList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //创建试卷按钮
    createTestPaper() {
      this.$router.push(
        "/examPaperLibrary/examPaperLibrary/management/createTestPaper"
      );
    },
    //编辑按钮
    editTestPaper(val) {
      console.log("编辑");
      this.$router.push(
        "/examPaperLibrary/examPaperLibrary/management/createTestPaper?examinationPaperSummaryId=" +
          val.examinationPaperSummaryId
      );
    },
    //编辑按钮
    deletaPaper(val) {
      this.$confirm("确定要删除试卷吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delSummary(val.examinationPaperSummaryId).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getTableData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //预览按钮
    goPreviewView(val) {
      this.$router.push(
        "/examPaperLibrary/examPaperLibrary/management/previewView?examinationPaperSummaryId=" +
          val.examinationPaperSummaryId
      );
    },
    //发布考试
    releaseExam(val){
        this.$router.push('/examination/addExamination?id='+val.examinationPaperSummaryId)
    }
  },
};
</script>
<style scoped lang="scss">
.box {
  height: 100%;
  width: 100%;
  background-color: #f1f3f8;
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  .left {
    height: 100%;
    width: 400px;
    // width: 265px;
    background-color: white;
    overflow: auto;
    .Ltitle {
      font-size: 16px;
      padding: 0 15px;
      line-height: 50px;
      display: flex;
      align-items: center;

      span {
        margin-right: 15px;
      }
      img {
        height: 15px;
        width: 15px;
        margin-right: 15px;
      }
      img:nth-of-type(1) {
        transform: rotateZ(90deg);
      }
      img:nth-of-type(2),
      img:nth-of-type(3) {
        opacity: 0.5;
      }
    }
    .Lline {
      height: 1px;
      background-color: #f1f3f8;
    }
    .Ltree {
      padding: 15px 0;
      height: calc(100% - 51px);
      overflow: auto;
      // width: 500px;

      .el-input {
        width: 50%;
        margin-right: 8px;
      }
      ::v-deep .el-tree-node {
        padding: 5px 0;
      }
    }
  }
  .right {
    height: 100%;
    width: calc(100% - 415px);
    // width: calc(100% - 280px);
    overflow: auto;
    // background-color: white;
    margin-left: 15px;
    padding: 0 15px;
    box-sizing: border-box;
    .RForm {
      display: flex;
      align-items: center;
      height: 120px;
      padding-left: 15px;
      background-color: white;
      > .el-form {
        flex: 1;
      }
      .el-form-item {
        // width: 15%;
        margin-bottom: 10px;
        min-width: 100px;
        ::v-deep .el-form-item__content {
          // width: 100%;
        }
      }
    }
    .rBottom {
      padding-top: 15px;
      height: calc(100% - 80px - 60px - 15px);
      overflow: auto;
      .rItem {
        height: 100px;
        background-color: white;
        margin-bottom: 15px;
        display: flex;
        justify-content: space-between;
        padding: 0 15px;
        .rItemLeft {
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;
          > div:nth-of-type(1) {
            font-size: 16px;
          }
          > div:nth-of-type(2) {
            font-size: 12px;
            color: #656577;
          }
          > div:nth-of-type(3) {
            font-size: 12px;
            color: #656577;
          }
        }
        .rItemRight {
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;
          > div:nth-of-type(1) {
            font-size: 12px;
            color: #656577;
            align-self: flex-end;
            span {
              margin: 0 5px;
            }
          }
          > div:nth-of-type(2) {
            .el-button {
              color: black;
              margin-left: 20px;
              font-size: 12px;
              i {
                color: #3a63f3;
                margin-right: 2px;
              }
            }
          }
        }
      }
      .rItem:nth-last-of-type(1) {
        margin-bottom: 0px;
      }
    }
  }
}

.label {
  span {
    margin-right: 15px;
  }
}
.el-icon-edit {
  color: #f1f3f8;
}

.el-tree-node {
  .custom-tree-node {
    line-height: 30px;
  }
  > .el-tree-node__content:hover {
    .label {
      display: inline-block;
    }
  }
  .label {
    display: none;
  }
}

.is-current {
  > .el-tree-node__content:nth-of-type(1) {
    .label {
      display: inline-block;
    }
  }
}

.el-tree {
  .el-tree-node__content {
    display: block !important;
  }
  .el-tree-node__children {
    overflow: visible !important;
  }
}
::v-deep .el-tree-node > .el-tree-node__children {
  overflow: visible;
}
::v-deep .el-tree--highlight-current .el-tree-node {
  min-width: max-content;
}
::v-deep .el-dialog {
  min-width: 500px;
}
.pagination-container {
  background-color: rgba($color: #000000, $alpha: 0);
}
</style>
